import { Form, Input, Select, Checkbox, Dialog, Row, Col, Button, MessagePlugin, Divider } from 'tdesign-react';
import React, { useEffect, useState } from 'react';
import FormItem from 'tdesign-react/es/form/FormItem';
import { addEmployee, User } from 'services/employee';

interface EmployeeModalProps {
  visible: boolean;
  isEdit: boolean;
  initialData?: Record<string, any>;
  onSave: (data: User) => void;
  onCancel: () => void;
}
const EmployeeModal: React.FC<EmployeeModalProps> = ({ visible, isEdit, initialData, onSave, onCancel }) => {
  const [form] = Form.useForm();


  useEffect(() => {
    if (initialData) {
      const reversePosition = (pos: number): string => {
        const positionMap: Record<number, string> = {
          1: '客服',
          2: '物流专员',
          3: '财务',
          4: '人事',
          5: '管理员'
        };
        return positionMap[pos] || '';
      };

      const reversePermissions = (perms: number[]): string[] => {
        const permissionMap: Record<number, string> = {
          1: '在线下单',
          2: '订单管理',
          3: '员工管理',
          4: '财务管理'
        };
        return perms.map(p => permissionMap[p]).filter(Boolean);
      };

      form.setFieldsValue({
        ...initialData,
        position: reversePosition(initialData.position),
        permissions: reversePermissions(initialData.permissions || [])
      });
    } else {
      form.reset();
    }
  }, [initialData, form, visible]);


  useEffect(() => {
    if (initialData) {
      form.setFieldsValue({
        ...initialData,
        // 确保 registered 有默认值
        registered: initialData.registered || 'active'
      });
    } else {
      // 设置新员工的默认值
      form.setFieldsValue({
        registered: 'active'
      });
    }
  }, [initialData, form]);

  // 岗位映射工具
  const mapPosition = (position: string): number => {
    const positionMap: Record<string, number> = {
      '客服': "1",
      '物流专员': " 2",
      '财务': "3",
      '人事': "4",
      '管理员': "5"
    };
    return positionMap[position] || 0; // 0 表示未知岗位
  };

  // 权限映射工具
  const mapPermissions = (permissions: string[]): number[] => {
    const permissionMap: Record<string, number> = {
      '在线下单': "1",
      '订单管理': "2",
      '员工管理': " 3",
      '财务管理': "4"
    };

    return permissions.map((p) =>
       permissionMap[p]).filter((id) => id !== undefined); // 过滤无效权限
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      // 使用更兼容的验证方式
      const validateResult = await form.validate();

      if (validateResult === true) {
        // 验证通过的处理
        const formData = form.getFieldsValue(true);
        // 映射岗位和权限为数字
        const mappedPosition = mapPosition(formData.position);
        const mappedPermissions = mapPermissions(formData.permissions || []);
        MessagePlugin.info('提交成功');



        onSave({
          ...formData,
          nick_name: formData.nick_name || '',
          company_id: '998a5805-ff3d-477d-a598-8348db542ccf',
          created_at: new Date().toISOString(),
          validateResult: {},
          phone: formData.phone || '',
          job_number: formData.job_number || '',
          position: mappedPosition,
          permissions: mappedPermissions,
          updated_at: new Date().toISOString(),
          registered: formData.registered || 'active'
        });
        onCancel();
      } else {
        // 验证失败的处理（validateResult 是错误对象）
        console.error('表单验证未通过，错误字段：', Object.keys(validateResult));
      }
    } catch (error) {
      console.error('表单验证失败', error);
    }

  }
  return (
    <>
      {' '}
      <Dialog
        visible={visible}
        header={initialData ? '修改权限' : '添加员工'}
        onCancel={onCancel}
        onConfirm={handleSubmit}
        onClose={onCancel}
        width={600}
      >
        <Divider style={{ margin: '0px', color: 'black', position: 'absolute' }} />
        <Form
          form={form}
          initialData={initialData}
          labelAlign='top'
          layout='vertical'
          labelWidth={50}
          onSubmit={handleSubmit}
          style={{ margin: '40px 0', maxHeight: 'calc(100vh - 200px)', padding: '0 24px' }}
        >
          <div style={{ marginBottom: 60, display: 'flex', gap: 16, position: 'relative' }} >
            <h4 style={{ position: 'absolute', top: -30, left: 0, margin: '0 -25px' }}>基础信息</h4>
            <Row gutter={16}>
              <Col span={12}>
                <FormItem name='nick_name' label='姓名' rules={[{ required: true, message: '请输入姓名' }]}>
                  <Input placeholder='请输入姓名' />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem name='phone' label='手机号' rules={[{ required: true, message: '请输入手机号' }]}>
                  <Input placeholder='请输入手机号' />
                </FormItem>

              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <FormItem name='job_number' label='工号' rules={[{ required: true, message: '请输入工号' }]}>
                  <Input placeholder='请输入工号' />
                </FormItem>
              </Col>
              <Col span={12}>
                <FormItem name='position' label='岗位' rules={[{ required: true, message: '请选择岗位' }]}>
                  <Select placeholder='请选择岗位'>
                    <Select.Option value='客服'>客服</Select.Option>
                    <Select.Option value='物流专员'>物流专员</Select.Option>
                    <Select.Option value='财务'>财务</Select.Option>
                    <Select.Option value='人事'>人事</Select.Option>
                    <Select.Option value='管理员'>管理员</Select.Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
          </div>

          <div style={{ marginBottom: 40, display: 'flex', gap: 16 }}>
            <h4 style={{ position: 'absolute', left: 0, margin: '-40px 35px' }}>权限设置</h4>
            <FormItem name='permissions'>
              <Checkbox.Group style={{ width: '100%' }}>
                <Row gutter={16}>
                  <Col span={12}>
                    <Checkbox value='在线下单'>在线下单</Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox value='订单管理'>订单管理</Checkbox>
                  </Col>
                </Row>
                <Row gutter={16} style={{ marginTop: 8 }}>
                  <Col span={12}>
                    <Checkbox value='员工管理'>员工管理</Checkbox>
                  </Col>
                  <Col span={12}>
                    <Checkbox value='财务管理'>财务管理</Checkbox>
                  </Col>
                </Row>
              </Checkbox.Group>
            </FormItem>
          </div>
        </Form>
        <Divider style={{ margin: '0px', color: 'black' }} />

      </Dialog>
    </>
  );
};

export default EmployeeModal;

function setIsModalVisible(arg0: boolean) {
  throw new Error('Function not implemented.');
}

